package org.vaadin.vaadinjit.data;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Simple recursive default implementation of the data structure for JitTreeData
 * 
 * @author jonkka
 *
 */
public class DefaultJitTreeData implements JitTreeData {

	private String id;
	private String name;
	private List<JitTreeData> children;
	
	private JitTreeData parent;
	
	/**
	 * Create a new node with the specified id and name
	 * 
	 * @param id the ID
	 * @param name the name
	 */
	public DefaultJitTreeData(String id, String name) {
		parent = null;
		this.id = id;
		this.name = name;
		this.children = new ArrayList<JitTreeData>();
	}
	
	
	@Override
	public String getId() {
		return id;
	}
	
	@Override
	public String getName() {
		return name;
	}
	
	
	public List<JitTreeData> getChildren() {
		return children;
	}
	
	
	@Override
	public String toJSON() {
		StringBuilder sBuilder = new StringBuilder();
		sBuilder.append("{");
		sBuilder.append("id: '" + this.getId() + "',");
		sBuilder.append("name: '" + this.getName() + "',");
		sBuilder.append("data: {},"); // Not supported for now
		sBuilder.append("children: [");
		for (Iterator<JitTreeData> iter = children.iterator(); iter.hasNext();) {
			JitTreeData child = iter.next();
			sBuilder.append(child.toJSON());
			if (iter.hasNext())
				sBuilder.append(",");
		}
		sBuilder.append("]");
		sBuilder.append("}");
		return sBuilder.toString();
	}


	@Override
	public void addChild(JitTreeData subTree) {
		subTree.setParent(this);
		children.add(subTree);
		
	}


	@Override
	public void removeChild(JitTreeData subTree) {
		
		if(children.remove(subTree)) {
			subTree.setParent(null);
		}
	}


	@Override
	public JitTreeData getParent() {
		return parent;
	}


	@Override
	public void setParent(JitTreeData parent) {
		this.parent = parent;
	}
}
